using System;
using UnityEngine;

#if UNITY_WEBGL && UNITY_EDITOR == false
using ClientType = UnityX.WebSocketClient;
#else
using ClientType = CSharpX.Network.Client;
#endif

namespace UnityX
{
    public class NetworkClient : MonoBehaviour
    {
        public static ClientType client;
        public string hostNameOrAddress = "127.0.0.1";
        public int prot = 12321;
#if UNITY_WEBGL
        public bool wss = true;
#endif

        private void Awake()
        {
#if UNITY_WEBGL && UNITY_EDITOR == false
            client = new UnityX.WebSocketClient(hostNameOrAddress, prot, CSharpX.Network.NetworkDefined.DefaultBufferSize, wss);
#else
            client = new CSharpX.Network.Client(hostNameOrAddress, prot);
#endif
            client.message.Connected += Connected;
            client.message.Disconnect += Disconnect;
            client.message.Error += Error;
        }
        private void Start()
        {
            client.Open();
        }
        private void Update()
        {
            client.Update();
        }
        private void OnDestroy()
        {
            if (client != null)
            {
                client.Close();
                client = null;
            }
        }
        private void Connected()
        {
            Log.Event("连接服务器成功");
        }
        private void Disconnect()
        {
            Log.Warning("服务器连接断开");
        }
        private void Error(Exception exception)
        {
            Log.Error(exception);
        }
    }
}
